package com.aiyige.page.my.localVideo;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.aiyige.MyApp;
import com.aiyige.R;
import com.aiyige.arouter.config.ARouterConfig;
import com.aiyige.base.BaseFragment;
import com.aiyige.page.detail.decoration.MyRecyclerViewDivider;
import com.aiyige.page.publish.util.PublishUtil;
import com.aiyige.track.annotation.Track;
import com.aiyige.utils.ListUtil;
import com.aiyige.utils.ToastX;
import com.aiyige.utils.UIHelper;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.vondear.rxtools.RxFileTool;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by xiachao on 2017/11/29.
 */
@Track("本地视频")
@Route(path = ARouterConfig.LocalVideoPage)
public class MyLocalMoviePage extends BaseFragment implements MyLocalMovieAdapter.DeleteCallback {

    private static final String TAG = "MyViewPage";

    private final int RESULT_ADD = 1;

    MyLocalMovieAdapter adapter;


    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;

    @BindView(R.id.tv_edit)
    TextView tvEdit;

    @BindView(R.id.btn_add)
    ImageView tvAdd;


    boolean selectAll = false;

    private boolean isEdit = false;

    @BindView(R.id.rl_bottom)
    RelativeLayout llBottom;

    @BindView(R.id.iv_item_selection)
    ImageView tvSelection;

    LinearLayoutManager linearLayoutManager;

    private List<LocalMovieInfo> list = new ArrayList<>();

    private LocalMovieDao localDao;

    @BindView(R.id.nodata)
    NodataView nodataView;


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.page_local_movie, container, false);
        ButterKnife.bind(this, view);
        initViews();
        return view;
    }

    private void initViews() {
        localDao = new LocalMovieDao();
        adapter = new MyLocalMovieAdapter();
        adapter.setCallback(this);
        linearLayoutManager = new LinearLayoutManager(getActivity());
        recyclerView.setLayoutManager(linearLayoutManager);
        recyclerView.addItemDecoration(new MyRecyclerViewDivider(
                getActivity(), LinearLayoutManager.VERTICAL, UIHelper.dip2px(getActivity(), 1), R.color.zwcolor_gray_f4f8f9));
        recyclerView.setAdapter(adapter);
        initData();
    }

    protected void initData() {
        new AsyncTask() {
            @Override
            protected Object doInBackground(Object[] params) {
                List<LocalMovieInfo> data = localDao.queryLocalMovies();
                List<LocalMovieInfo> existMovies = new LinkedList<LocalMovieInfo>();
                for (LocalMovieInfo info : data) {
                    if (RxFileTool.isFileExists(info.path)) {
                        existMovies.add(info);
                    } else {
                        localDao.removeLocalMovie(info);
                    }
                }
                return existMovies;
            }

            @Override
            protected void onPostExecute(Object o) {
                list.clear();
                list.addAll((List<LocalMovieInfo>) o);
                adapter.replaceData(list);
                adapter.notifyDataSetChanged();
                showNodataView();
            }
        }.execute();
    }

    private void showNodataView() {
        if (null == list || list.isEmpty()) {
            nodataView.showNodataView();
            setEdit(false);
            editEnabled(false);
        } else {
            nodataView.hideView();
            editEnabled(true);
        }
    }

    private void setSelectAll() {
        if (adapter == null) {
            return;
        }
        adapter.selectAll();
    }

    private void setUnSelectAll() {
        if (adapter == null) {
            return;
        }
        adapter.unSelectAll();
    }

    private void deleteSelected() {
        if (adapter == null) {
            return;
        }
        if (adapter.getSelectedList() == null || adapter.getSelectedList().isEmpty()) {
            ToastX.show(MyApp.getAppContext().getString(R.string.please_select_local_videos_data));
            return;
        }
        new AlertDialog.Builder(getActivity()).setTitle(getString(R.string.alert_delete))
                .setPositiveButton(getString(R.string.confirm), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (!ListUtil.isEmpty(adapter.getSelectedList())) {
                            for (LocalMovieInfo info : adapter.getSelectedList()) {
                                localDao.removeLocalMovie(info);
                            }
                        }
                        adapter.deleteSelected();
                        if (ListUtil.isEmpty(adapter.getData())) {
                            setEdit(false);
                        }
                        dialog.dismiss();
                    }
                }).setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        }).show();

    }

    public void setEdit(boolean edit) {
//        if (adapter.getData() == null
//                || adapter.getData().isEmpty()) {
//            deleteCallback();
//            return;
//        }
        isEdit = edit;
        adapter.setEdit(isEdit);
        tvEdit.setText(getString(isEdit ? R.string.cancel_edit : R.string.edit));
        llBottom.setVisibility(isEdit ? View.VISIBLE : View.GONE);
        tvAdd.setVisibility(isEdit ? View.GONE : View.VISIBLE);
    }

    @OnClick({R.id.tv_edit, R.id.ll_select_all, R.id.tv_delete, R.id.btn_add})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_edit:
                setEdit(!isEdit);
                break;
            case R.id.ll_select_all:
                selectAll = !selectAll;
                tvSelection.setSelected(selectAll);
                if (selectAll) {
                    setSelectAll();
                } else {
                    setUnSelectAll();
                }
                break;
            case R.id.tv_delete:
                deleteSelected();
                break;
            case R.id.btn_add:
                PictureSelector.create(getActivity())
                        .openGallery(PictureMimeType.ofVideo())
                        .isCamera(false)
                        .previewImage(false)
                        .previewVideo(false)
                        .maxSelectNum(PublishUtil.MAX_PUBLISH_LEARN_VIDEO_NUM)
                        .selectionMedia(getSelectedVideo())
                        .minSelectNum(1)
                        .selectionMode(PictureConfig.MULTIPLE)
                        .forResult(RESULT_ADD);
                break;
        }
    }

    public List<LocalMedia> getSelectedVideo() {
        if (list == null || list.isEmpty()) {
            return null;
        }
        List<LocalMedia> localMediaList = new LinkedList<>();
        for (LocalMovieInfo item : list) {
            LocalMedia localMedia = new LocalMedia();
            localMedia.setPictureType("video/mp4");
            localMedia.setMimeType(PictureConfig.TYPE_VIDEO);
            localMedia.setPath(item.getPath());
            localMediaList.add(localMedia);
        }
        return localMediaList;
    }

    public void editEnabled(boolean enabled) {
        tvEdit.setTextColor(ContextCompat.getColor(getActivity(), enabled ? R.color.zwcolor_black_111111 : R.color.zwcolor_gray_b1b5c1));
        tvEdit.setEnabled(enabled);
        if (isEdit) {
            tvEdit.setText(getString(!enabled ? R.string.edit : R.string.cancel_edit));
            llBottom.setVisibility(enabled ? View.VISIBLE : View.GONE);
            if (!enabled) {
                selectAll = false;
                tvSelection.setSelected(selectAll);
            }
        }
    }

    @Override
    public void deleteCallback() {
        boolean isEmpty = adapter.getData() == null
                || adapter.getData().isEmpty();
        editEnabled(!isEmpty);
        initData();
    }

    @Override
    public void unSelectCallback() {
        if (selectAll) {
            selectAll = !selectAll;
            tvSelection.setSelected(selectAll);
        }
    }

//    @Override
//    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//        if (resultCode == RESULT_CANCELED) {
//            return;
//        }
//        if (requestCode == RESULT_ADD) {
//            saveBySelfPhoto(data);
//        }
//    }

    /**
     * 添加视频回调
     * @param data
     */
    public void onResult(Intent data) {
        saveBySelfPhoto(data);
    }

    /**
     * 通过自己相册取视频
     *
     * @param data
     */
    private void saveBySelfPhoto(Intent data) {
        List<LocalMedia> selectList = PictureSelector.obtainMultipleResult(data);
        if (!ListUtil.isEmpty(selectList)) {
            for (LocalMedia localMedia : selectList) {
                LocalMovieInfo info = new LocalMovieInfo();
                info.setPath(localMedia.getPath());
                info.setFileName(getFileName(RxFileTool.getFileName(localMedia.getPath())));
                info.setDuration(localMedia.getDuration());
                info.setDateTime(System.currentTimeMillis());
                if (RxFileTool.isFileExists(localMedia.getPath())) {
                    info.setSize(RxFileTool.getFileAllSize(localMedia.getPath()));
                }
                if (!localDao.isHasAdd(localMedia.getPath())) {
                    localDao.addLocalMovie(info);
                }
            }
            initData();
        }
    }

    private String getFileName(String fileName) {
        String name = "";
        if (TextUtils.isEmpty(fileName)) {
            return "";
        }
        if (fileName.contains(".")) {
            String names[] = fileName.split("\\.");
            if (names != null && names.length > 0) {
                name = names[0];
            }
        }
        return name;

    }
}
